import request from '@/utils/request'
import { handleBaasData, setPublishReadAcl } from '@/utils/baasDataFilter'
import { log } from './log.js'

export function fetch(className, query) {
  const logData = {
    className: className,
    query: JSON.stringify(query)
  }
  log('fetch', 'KerustStore', logData)
  return request({
    url: 'object/' + className,
    method: 'get',
    params: query
  })
}

export function getObjectById(className, id) {
  const logData = {
    className: className,
    id: id
  }
  log('getObjectById', 'KerustStore', logData)
  return request({
    url: 'object/' + className + '/' + id,
    method: 'get'
  })
}

export function insert(className, data) {
  const logData = {
    className: className,
    data: JSON.stringify(data)
  }
  log('insert', 'KerustStore', logData)
  handleBaasData(data)
  setPublishReadAcl(data)
  return request({
    url: 'object/' + className,
    method: 'post',
    data
  })
}

export function deleteById(className, id) {
  const logData = {
    className: className,
    id: id
  }
  log('deleteById', 'KerustStore', logData)
  return request({
    url: 'object/' + className + '/' + id,
    method: 'delete'
  })
}

export function deleteByQuery(className, query) {
  const logData = {
    className: className,
    query: JSON.stringify(query)
  }
  log('deleteByQuery', 'KerustStore', logData)
  return request({
    url: 'object/' + className + '/deleteByQuery',
    method: 'delete',
    params: query
  })
}

export function update(className, id, data) {
  const logData = {
    className: className,
    id: id,
    data: JSON.stringify(data)
  }
  log('update', 'KerustStore', logData)
  handleBaasData(data)
  return request({
    url: 'object/' + className + '/' + id,
    method: 'put',
    data
  })
}

export function cloud(cloudName, params) {
  const logData = {
    cloudName: cloudName,
    params: JSON.stringify(params)
  }
  log('cloud', 'KerustStore', logData)
  return request({
    url: 'cloud/' + cloudName,
    method: 'get',
    params: params
  })
}

export function login(params) {
  const response = request({
    url: 'user/login',
    method: 'get',
    params: params
  })
  return response
}

export function updateUserInfo(id, data) {
  const logData = {
    id: id,
    data: JSON.stringify(data)
  }
  log('updateUserInfo', 'KerustStore', logData)
  return request({
    url: 'user/' + id,
    method: 'put',
    data
  })
}

export function updatePassword(id, data) {
  const logData = {
    id: id,
    data: JSON.stringify(data)
  }
  log('updatePassword', 'KerustStore', logData)
  return request({
    url: 'user/' + id + '/updatePassword',
    method: 'put',
    data
  })
}
